/************************************************************************
                                                                     
   Xceed Ultimate ListBox for Silverlight                                                                                                                                            
   Copyright (C) 2010 Xceed Software Inc.    
                                                                     
   This program is provided to you under the terms of the GNU General Public  
   License version 2 as published by the Free Software Foundation. 
        
   This program is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY, without even the implied warranty of 
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

   You should have received a copy of the GNU General Public License along 
   with this program, if not, write to the Free Software Foundation, Inc., 
   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

   This program can be provided to you by Xceed Software Inc. under a
   proprietary commercial license agreement for use in non-Open Source
   projects. Visit Xceed.com to find the commercial edition of 
   Xceed Ultimate ListBox for Silverlight.                                    
                                                                      
 **********************************************************************/

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using Xceed.Silverlight.Data.Utils;

namespace Xceed.Silverlight.Data
{
  internal class DataSourceCollection : ICollection, INotifyCollectionChanged, ISLWeakEventListener
  {
    internal DataSourceCollection( IEnumerable dataSource )
    {
      if( dataSource == null )
        throw new ArgumentNullException( "dataSource" );

      m_dataSource = dataSource;

      // Listen to notification events if they are supported.
      INotifyCollectionChanged observableCollection = dataSource as INotifyCollectionChanged;
      if( observableCollection != null )
      {
        SLCollectionChangedEventManager.AddListener( observableCollection, this );
      }

      // Retrieve the type of the items in the collection.
      m_elementType = DataSourceCollection.GetElementType( dataSource.GetType() );
      if( m_elementType == null )
      {
        m_elementType = typeof( object );
      }
    }


    #region Count Property

    public int Count
    {
      get
      {
        lock( ( ( ICollection )this ).SyncRoot )
        {
          ICollection sourceCollection = this.GetSourceCollection();
          int count = 0;

          if( sourceCollection != null )
          {
            count = sourceCollection.Count;
          }
          else
          {
            foreach( object item in this.GetSourceEnumerable() )
            {
              count++;
            }
          }

          return count;
        }
      }
    }

    #endregion

    #region ElementType Property

    internal Type ElementType
    {
      get
      {
        return m_elementType;
      }
    }

    private Type m_elementType;

    #endregion


    #region CollectionChanged Event

    public event NotifyCollectionChangedEventHandler CollectionChanged;

    #endregion


    public IEnumerator GetEnumerator()
    {
      return this.GetSourceEnumerable().GetEnumerator();
    }

    private ICollection GetSourceCollection()
    {
      ICollection sourceCollection = m_dataSource as ICollection;

      // Try to get a ICollection from a ICollectionView.
      if( sourceCollection == null )
      {
        ICollectionView collectionView = m_dataSource as ICollectionView;

        if( collectionView != null )
        {
          sourceCollection = collectionView.SourceCollection as ICollection;
        }
      }

      return sourceCollection;
    }

    private IEnumerable GetSourceEnumerable()
    {
      IEnumerable sourceEnumerable = m_dataSource;
      ICollectionView collectionView = sourceEnumerable as ICollectionView;

      if( collectionView != null )
      {
        sourceEnumerable = collectionView.SourceCollection;
      }

      return sourceEnumerable;
    }

    private static Type GetElementType( Type dataSourceType )
    {
      if( dataSourceType != null )
      {
        if( dataSourceType.IsArray )
          return dataSourceType.GetElementType();

        // Find out the element type through the IEnumerable<> interface.
        foreach( Type interfaceType in dataSourceType.GetInterfaces() )
        {
          if( ( interfaceType.IsGenericType ) && ( interfaceType.GetGenericTypeDefinition() == typeof( IEnumerable<> ) ) )
          {
            return interfaceType.GetGenericArguments()[ 0 ];
          }
        }
      }

      return null;
    }


    #region ICollection Members

    bool ICollection.IsSynchronized
    {
      get
      {
        return true;
      }
    }

    object ICollection.SyncRoot
    {
      get
      {
        return m_syncRoot;
      }
    }

    void ICollection.CopyTo( Array array, int index )
    {
      if( array == null )
        throw new ArgumentNullException( "array" );

      ICollection self = this;
      lock( self.SyncRoot )
      {
        foreach( object item in self )
        {
          array.SetValue( item, index );
          index++;
        }
      }
    }

    #endregion

    #region IWeakEventListener Members

    bool ISLWeakEventListener.ReceiveWeakEvent( Type managerType, object sender, EventArgs e )
    {
      if( managerType == typeof( SLCollectionChangedEventManager ) )
      {
        if( this.CollectionChanged != null )
        {
          this.CollectionChanged( this, ( NotifyCollectionChangedEventArgs )e );
        }

        return true;
      }

      return false;
    }

    #endregion


    #region Private Fields

    private IEnumerable m_dataSource;
    private object m_syncRoot = new object();

    #endregion
  }
}
